import {useEffect, useMemo, useState} from 'react';
import {Button, Form, Row, message} from "antd";
import CycleForm from "@/components/DynamicSearchForm/CycleForm.tsx";
import PageModule from "@/components/PageModule.tsx";
import RegisterCode from "./RegisterCode.tsx";
import {sessionGet, sessionDelete} from "@/utils/storage.ts";
import {addressEcho, addressSubmit} from "@/components/AddressPart/address.ts";
import {insertOrg, orgSearchNameList, queryOrgClassBySuperCode, updateOrg} from '@/axios/apis.ts'
import {getOrganizationForLogged} from '@/utils/organization.ts'
import {useSelector} from 'react-redux'
import {getDicOnCode} from "@/utils/dicAll.ts";
import {useSearchParams, useNavigate} from 'react-router-dom'

const OrganAdd = () => {
    const addressKey = {
        provinceCode: 'orgPrivoncecode',
        provinceName: 'orgPrivonceName',
        cityCode: 'orgCitycode',
        cityName: 'orgCityName',
        regionCode: 'regionCode',
        regionName: 'regionName'
    }
    const [searchParams] = useSearchParams()
    const navigate = useNavigate()
    const pageType: string | null = searchParams.get('type');
    const {userInfo} = useSelector((state: any) => state.userSlice)
    const [form] = Form.useForm();
    // 额外的字段
    const [extraFields, setExtraFields] = useState({})
    const [fields, setFields] = useState<FormFields>([])
    const queryOption = () => {
        Promise.all([
            getOrganizationForLogged(userInfo.powers),
            orgSearchNameList(),
        ]).then(res => {
            const [res1, res2] = res
            const list: FormFields = [
                {
                    type: 'AddressPart',
                    name: 'addressPart',
                    label: '所在省市',
                    showArea: false,
                    rules: [{required: true, message: '所在省市区/县'}],
                },
                {
                    type: 'cascader',
                    name: 'orgSuperCode',
                    label: '上级机构',
                    placeholder: '请选择',
                    options: res1?.data || [],
                    fieldNames: {
                        label: 'orgName', value: 'orgCode', children: 'orgChildrenMap'
                    },
                    rules: [{required: true, message: '请选择上级机构'}],
                    onChange: (orgSuperCode, context) => {
                        setExtraFields({
                            ...extraFields,
                            orgSuperName: context.node.data.orgName
                        })
                        queryOrgClassBySuperCode({orgSuperCode}).then(res => {
                            if (+res.code === 200) {
                                form.setFieldValue('orgClass', res.data.orgClass)
                                console.log(form.getFieldsValue())
                            }
                        })
                    }
                },
                {
                    type: 'select',
                    name: 'orgClass',
                    label: '机构级别',
                    options: getDicOnCode("SYS.ORGS"),
                    disabled: true,
                },
                {
                    type: 'input',
                    name: 'orgShortName',
                    label: '机构简称',
                    rules: [{required: true, message: '请输入机构简称'}]
                },
                {
                    type: 'input',
                    name: 'orgName',
                    label: '机构名称',
                    rules: [{required: true, message: '请输入机构名称'}]
                },
                {
                    type: 'select',
                    name: 'status',
                    label: '机构状态',
                    options: getDicOnCode("SYS.STATUS"),
                    disabled: true,
                },
                {
                    type: 'input',
                    name: 'orgTelephone',
                    label: '联系电话',
                },
                {
                    type: 'input',
                    name: 'orgAddress',
                    label: '详细地址',
                },
                {
                    type: 'select',
                    name: 'listingFlag',
                    label: '是否持牌',
                    options: getDicOnCode("SYS.ISNOT"),
                    rules: [{required: true, message: '请选择是否持牌'}]
                },
                {
                    type: 'select',
                    name: 'personInChargeId',
                    label: '审批节点',
                    options: res2?.data || [],
                    optionRender: (option: object) => (
                        <div>
                            <span>{option.data.showName}</span>
                            <span style={{float: 'right'}}>{option.data.userName}</span>
                        </div>
                    ),
                    fieldNames: {
                        label: 'showName', value: 'userName', options: 'options'
                    }
                },
                {
                    type: 'input',
                    name: 'responsiblePeople',
                    label: '负责人',
                },
                {
                    type: 'input',
                    name: 'orgResponsiblePhone',
                    label: '负责人电话',
                },
                {
                    type: 'input',
                    name: 'unifiedCreditCode',
                    label: '统一社会信用代码',
                    maxLength: 18,
                    rules: [{required: true, message: '请输入统一社会信用代码'}]
                },
            ]
            if (pageType === 'details') {
                list.splice(12, 0, {
                    type: 'input',
                    name: 'endTime',
                    label: '注销时间',
                });
            }
            setFields(list)
        })
    }
    useEffect(() => {
        queryOption()
        setExtraFields({
            ...extraFields,
            createUserId: userInfo.id,
            createUserName: userInfo.showName,
        })
    }, [userInfo])
    useEffect(() => {
        let params = sessionGet('organDetails')
        if (params) {
            params = addressEcho(params, addressKey)
            form.setFieldsValue(params)
        }
        if (['edit', 'details'].includes(pageType)) {
            setExtraFields({
                ...extraFields,
                id: params?.id,
                orgCode: params?.orgCode
            })
        }
        return () => {
            sessionDelete('organDetails')
        };
    }, [])
    const disabled = useMemo(() => {
        return pageType === 'details'
    }, [pageType])
    const onFinish = (values) => {
        const params: object = {...addressSubmit(values, addressKey), ...extraFields}
        if (pageType === 'add') {
            insertOrg(params).then(res => {
                if (res.code === 200) {
                    if (res.data == 'success') {
                        message.success('新增成功')
                        navigate('/organManage')
                    } else {
                        message.error(res.data)
                    }

                }
            })
        } else if (pageType === 'edit') {
            updateOrg(params).then(res => {
                if (res.code === 200) {
                    if (res.data == 'success') {
                        message.success('编辑成功')
                        navigate('/organManage')
                    } else {
                        message.error(res.data)
                    }
                }
            })
        }
    }
    return (
        <>
            <PageModule title="机构设置">
                <Form
                    form={form}
                    layout="horizontal"
                    autoComplete="off"
                    labelCol={{span: 7}}
                    wrapperCol={{span: 17}}
                    onFinish={onFinish}
                    disabled={disabled}
                    initialValues={{status: '1'}}
                >
                    <Row>
                        <CycleForm fields={fields} form={form} disabled={disabled} />
                    </Row>
                    {!disabled && <div style={{height: 40, lineHeight: 6, textAlign: 'center'}}>
                        <Button className="mr15" type="primary" htmlType="submit">保存</Button>
                        <Button htmlType="reset">清空</Button>
                    </div>}
                </Form>
            </PageModule>
            <PageModule title="二维码" btns={<span className="qrCodetips">（仅限传统业务人员注册执业证使用）</span>}>
                <RegisterCode code={extraFields.orgCode} />
                <div className="ml15">{form.getFieldValue('orgName')}</div>
            </PageModule>
        </>
    );
};

export default OrganAdd;